/*
 *  CDisplay.cpp
 *  TestRPG
 *
 *  Created by Michael Rhodes on 10-05-30.
 *  Copyright 2010 __MyCompanyName__. All rights reserved.
 *
 */

#include "../Tigerengine.h"

// -----------------------------------------------------------------------
// InitDisplay()
// 
//		Initialize the main display.  This will create a window, fullscreen
//		or not, and setup the OpenGL environment for rendering.
// -----------------------------------------------------------------------
int CDisplay::InitDisplay(int width, int height, int bits, bool fs, wchar_t* title)
{
	GLuint		PixelFormat;			// Holds The Results After Searching For A Match
	WNDCLASS	wc;						// Windows Class Structure
	DWORD		dwExStyle;				// Window Extended Style
	DWORD		dwStyle;				// Window Style
	RECT		WindowRect;				// Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left=(long)0;			// Set Left Value To 0
	WindowRect.right=(long)width;		// Set Right Value To Requested Width
	WindowRect.top=(long)0;				// Set Top Value To 0
	WindowRect.bottom=(long)height;		// Set Bottom Value To Requested Height

	m_bFullscreen=fs;					// Set The Global Fullscreen Flag
	m_ScreenWidth = width;
	m_ScreenHeight = height;
	m_ScreenBpp = bits;

	m_hInstance			= GetModuleHandle(NULL);				// Grab An Instance For Our Window
	wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// Redraw On Size, And Own DC For Window.
	wc.lpfnWndProc		= WndProc;								// WndProc Handles Messages
	wc.cbClsExtra		= 0;									// No Extra Window Data
	wc.cbWndExtra		= 0;									// No Extra Window Data
	wc.hInstance		= m_hInstance;							// Set The Instance
	wc.hIcon			= LoadIcon(NULL, IDI_WINLOGO);			// Load The Default Icon
	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);			// Load The Arrow Pointer
	wc.hbrBackground	= NULL;									// No Background Required For GL
	wc.lpszMenuName		= NULL;									// We Don't Want A Menu
	wc.lpszClassName	= WNDCLASS_NAME;								// Set The Class Name

	if (!RegisterClass(&wc))									// Attempt To Register The Window Class
	{
		MSGBOX("Failed To Register The Window Class.","ERROR");
		return FALSE;											// Return FALSE
	}
	
	if (m_bFullscreen)												// Attempt Fullscreen Mode?
	{
		DEVMODE dmScreenSettings;								// Device Mode
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));	// Makes Sure Memory's Cleared
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode Structure
		dmScreenSettings.dmPelsWidth	= width;				// Selected Screen Width
		dmScreenSettings.dmPelsHeight	= height;				// Selected Screen Height
		dmScreenSettings.dmBitsPerPel	= bits;					// Selected Bits Per Pixel
		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		// Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
		{
			// If The Mode Fails, Offer Two Options.  Quit Or Use Windowed Mode.
			if (MessageBox(NULL,__TEXT("The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?"),__TEXT("NeHe GL"),MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
			{
				m_bFullscreen=FALSE;		// Windowed Mode Selected.  Fullscreen = FALSE
			}
			else
			{
				// Pop Up A Message Box Letting User Know The Program Is Closing.
				MSGBOX("Program Will Now Close.","ERROR");
				return FALSE;									// Return FALSE
			}
		}
	}

	if (m_bFullscreen)												// Are We Still In Fullscreen Mode?
	{
		dwExStyle=WS_EX_APPWINDOW;								// Window Extended Style
		dwStyle=WS_POPUP;										// Windows Style
		ShowCursor(FALSE);										// Hide Mouse Pointer
	}
	else
	{
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style
		dwStyle=WS_OVERLAPPEDWINDOW;							// Windows Style
	}

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size

	// Create The Window
	if (!(m_hMainWnd=CreateWindowEx(dwExStyle,						// Extended Style For The Window
								WNDCLASS_NAME,						// Class Name
								title,						// Window Title
								dwStyle |							// Defined Window Style
								WS_CLIPSIBLINGS |					// Required Window Style
								WS_CLIPCHILDREN,					// Required Window Style
								0, 0,								// Window Position
								WindowRect.right-WindowRect.left,	// Calculate Window Width
								WindowRect.bottom-WindowRect.top,	// Calculate Window Height
								NULL,								// No Parent Window
								NULL,								// No Menu
								m_hInstance,						// Instance
								NULL)))								// Dont Pass Anything To WM_CREATE
	{
		ShutdownDisplay();								// Reset The Display
		MSGBOX("Window Creation Error.","ERROR");
		return FALSE;								// Return FALSE
	}

	static	PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,							// Must Support Double Buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		bits,										// Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		PFD_MAIN_PLANE,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};
	
	if (!(m_hDC=GetDC(m_hMainWnd)))							// Did We Get A Device Context?
	{
		ShutdownDisplay();								// Reset The Display
		MSGBOX("Can't Create A GL Device Context.","ERROR");
		return FALSE;							// Return FALSE
	}

	if (!(PixelFormat=ChoosePixelFormat(m_hDC,&pfd)))	// Did Windows Find A Matching Pixel Format?
	{
		ShutdownDisplay();							// Reset The Display
		MSGBOX("Can't Find A Suitable PixelFormat.","ERROR");
		return FALSE;								// Return FALSE
	}

	if(!SetPixelFormat(m_hDC,PixelFormat,&pfd))		// Are We Able To Set The Pixel Format?
	{
		ShutdownDisplay();							// Reset The Display
		MSGBOX("Can't Set The PixelFormat.","ERROR");
		return FALSE;								// Return FALSE
	}

	if (!(m_hRC=wglCreateContext(m_hDC)))			// Are We Able To Get A Rendering Context?
	{
		ShutdownDisplay();							// Reset The Display
		MSGBOX("Can't Create A GL Rendering Context.","ERROR");
		return FALSE;								// Return FALSE
	}

	if(!wglMakeCurrent(m_hDC,m_hRC))				// Try To Activate The Rendering Context
	{
		ShutdownDisplay();							// Reset The Display
		MSGBOX("Can't Activate The GL Rendering Context.","ERROR");
		return FALSE;								// Return FALSE
	}

	ShowWindow(m_hMainWnd,SW_SHOW);					// Show The Window
	SetForegroundWindow(m_hMainWnd);				// Slightly Higher Priority
	SetFocus(m_hMainWnd);							// Sets Keyboard Focus To The Window
	ResizeGLScene(width, height);					// Set Up Our Perspective GL Screen
	
	if (!InitGL())									// Initialize Our Newly Created GL Window
	{
		ShutdownDisplay();							// Reset The Display
		MSGBOX("Initialization Failed.","ERROR");
		return FALSE;								// Return FALSE
	}

	return TRUE;				
} // int CDisplay::InitDisplay(GLuint w, GLuint h, GLuint bpp, GLboolean fs, std::string title)
int CDisplay::InitGL(void)
{
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);			// Set clear color to black
		
	// Disable OpenGL features not needed and that will interfere with 2D rendering.
	glDisable(GL_LIGHTING);
	glDisable(GL_DITHER);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_BLEND);

	// Call the resize method to set the viewport and projection matrix
	ResizeGLScene(m_ScreenWidth, m_ScreenHeight);

	return RET_SUCCESS;
} // int CDisplay::InitGL(void)
// -----------------------------------------------------------------------
// ShutdownDisplay()
//
//		Close the display system down and free any resources used.
// -----------------------------------------------------------------------
int CDisplay::ShutdownDisplay()
{
	if(m_bFullscreen)
	{
		ChangeDisplaySettings(NULL, 0);			// Switch back to desktop mode
		ShowCursor(TRUE);						// Make sure the cursor is visable
	} // if(m_bFullscreen)

	if(m_hRC)							// If we have a rendering context, properly
	{									// release it and make it NULL
		if(!wglMakeCurrent(NULL, NULL))
		{
			//MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}
		if(!wglDeleteContext(m_hRC))
		{
			//MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}
		m_hRC = NULL;
	} // if(m_hRC)

	if(m_hDC && !ReleaseDC(m_hMainWnd, m_hDC))
	{
		m_hDC = NULL;
	} // if(m_hDC && !ReleaseDC(m_hMainWnd, m_hDC))

	if(m_hMainWnd && !DestroyWindow(m_hMainWnd))
	{
		m_hMainWnd = NULL;
	} // if(m_hMainWnd && !DestroyWindow(m_hMainWnd))
	
	if(!UnregisterClass(WNDCLASS_NAME, m_hInstance))
	{
		m_hInstance = NULL;
	} // if(!UnregisterClass(WNDCLASS_NAME, m_hInstance))
	
	return TRUE;
} // int CDisplay::ShutdownDisplay()
/* --------------------------------------------------------
 * ResizeGLScene()
 *		Anytime the window is resized this method will be
 *		called to recreate the opengl ortho viewport.
 * ----------------------------------------------------- */
void CDisplay::ResizeGLScene(GLuint width, GLuint height)
{
	// Make height = at least 1 to avoid any problems
	if (height == 0)
		height = 1;
	
	glViewport(0, 0, width, height);
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	
	// Set up the window so the bottom left corner is (0,0)
	glOrtho(0.0f, width, 0.0f, height, -1.0f, 1.0f);
	
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();	
} // void CDisplay::resized(GLuint w, GLuint h)
void CDisplay::Flip(void)
{
	SwapBuffers(m_hDC);
}
CDisplay::CDisplay()
{
	m_hDC = NULL;
	m_hRC = NULL;
	m_hMainWnd = NULL;
	m_hInstance = NULL;
}
CDisplay::~CDisplay()
{


}


LRESULT CALLBACK CDisplay::WndProc(HWND	hWnd, UINT uMsg, WPARAM	wParam, LPARAM lParam)
{
	switch (uMsg)									// Check For Windows Messages
	{
		case WM_ACTIVATE:							// Watch For Window Activate Message
		{
			if (!HIWORD(wParam))					// Check Minimization State
			{
				g_pApp->SetActive(TRUE);				// Program Is Active
			}
			else
			{
				g_pApp->SetActive(FALSE);				// Program Is No Longer Active
			}
			return 0;								// Return To The Message Loop
		}

		case WM_SYSCOMMAND:							// Intercept System Commands
		{
			switch (wParam)							// Check System Calls
			{
				case SC_SCREENSAVE:					// Screensaver Trying To Start?
				case SC_MONITORPOWER:				// Monitor Trying To Enter Powersave?
				return 0;							// Prevent From Happening
			}
			break;									// Exit
		}

		case WM_CLOSE:								// Did We Receive A Close Message?
		{
			g_pApp->Shutdown();
			PostQuitMessage(0);						// Send A Quit Message
			return 0;								// Jump Back
		}
			
		case WM_SIZE:								// Resize The OpenGL Window
		{
			g_pApp->m_display->ResizeGLScene(LOWORD(lParam),HIWORD(lParam));  // LoWord=Width, HiWord=Height
			return 0;								// Jump Back
		}
		

		case WM_INPUT:
		{
			UINT	dwSize;

			GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER));

			LPBYTE lpb = new BYTE[dwSize];
			if(lpb == NULL)
			{
				return 0;
			}
			if(GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize)
			{
				DBGMSG("GetRawInputData doesn't return correct size.");
			}

			RAWINPUT *raw = (RAWINPUT*)lpb;

			// Check for each of the devices to get input from
			if(raw->header.dwType == RIM_TYPEKEYBOARD)
			{
				// Check if key is up or down
				if(raw->data.keyboard.Flags == RI_KEY_MAKE)
				{				
					// Check if this keypress has already been added to the queue as a keydown
					// If it has, then ignore this...  If not make a new entry in the queue for this
					// keypress

					// Perhaps keep a local copy of the key's that are currently being held down
					// so we won't have to query the queue everytime.
					g_pApp->m_input->OnKeyPress(raw->data.keyboard.VKey);
				}
				if(raw->data.keyboard.Flags == RI_KEY_BREAK)
					g_pApp->m_input->OnKeyRelease(raw->data.keyboard.VKey);
				
			} // if(raw->header.dwType == RIM_TYPEKEYBOARD)
			else if(raw->header.dwType == RIM_TYPEMOUSE)
			{

			} // else if(raw->header.dwType == RIM_TYPEMOUSE)
			else if(raw->header.dwType == RIM_TYPEHID)
			{
			
			} // else if(raw->header.dwType == RIM_TYPEHID)

			delete [] lpb;
			return 0;
		} // case WM_INPUT
		
	}

	// Pass All Unhandled Messages To DefWindowProc
	return DefWindowProc(hWnd,uMsg,wParam,lParam);
} // LRESULT CALLBACK CDisplay::WndProc(HWND	hWnd, UINT uMsg, WPARAM	wParam, LPARAM lParam)
